import { Injectable, effect, signal } from '@angular/core';
import { Subject } from 'rxjs';
import { ThemeService } from '../../services/theme.service';
import { LocalStorageService } from '../../local-storage.service';

const STATIC_MENU_DESKTOP_INACTIVE = 'STATIC_MENU_DESKTOP_INACTIVE';

export interface AppConfig {
  inputStyle: string;
  colorScheme: string;
  ripple: boolean;
  menuMode: string;
  scale: number;
}

interface LayoutState {
  staticMenuDesktopInactive: boolean;
  overlayMenuActive: boolean;
  profileSidebarVisible: boolean;
  configSidebarVisible: boolean;
  staticMenuMobileActive: boolean;
  menuHoverActive: boolean;
}

@Injectable({
  providedIn: 'root',
})
export class LayoutService {
  private darkTheme = {
    '--surface-a': '#0B1219', // Darker navy
    '--surface-b': '#070D17', // Very dark navy (from image)
    '--surface-c': 'rgba(255,255,255,0.03)',
    '--surface-d': '#1A2632', // Slightly lighter navy
    '--surface-e': '#0B1219',
    '--surface-f': '#0B1219',
    '--surface-ground': '#070D17',
    '--surface-section': '#070D17',
    '--surface-card': '#0B1219',
    '--surface-overlay': '#0B1219',
    '--surface-border': '#1A2632',
    '--surface-hover': 'rgba(255,255,255,0.03)',
    '--text-color': 'rgba(255, 255, 255, 0.87)',
    '--text-color-secondary': 'rgba(255, 255, 255, 0.6)',
    '--text-color-sidebar': '#EBF4FF', // Sidebar text color
    '--text-color-sidebar-active': '#FFFFFF', // Sidebar active text color
    '--text-bg-sidebar-active': 'var(--blue-700)', // Sidebar active bg color
    '--primary-color-text': '#ffffff',
    '--maskbg': 'rgba(0,0,0,0.4)',
    '--ansi-green': "#00ff00",
    '--ansi-yellow': "#ffff00",
    '--ansi-blue': "#0000ff",
    '--ansi-magenta': "#ff00ff",
    '--ansi-cyan': "#00ffff",
    '--ansi-white ': "ffffff;",
  };

  private lightTheme = {
    '--surface-a': '#FFFFFF', // Lighter navy for main background
    '--surface-b': '#F8FAFC', // Medium navy for secondary background
    '--surface-c': 'hsla(213, 76%, 50%, 0.1)',
    '--surface-d': '#D9E2EC', // Light navy for borders
    '--surface-e': '#FFFFFF',
    '--surface-f': '#FFFFFF',
    '--surface-ground': '#F8FAFC',
    '--surface-section': '#FFFFFF',
    '--surface-card': '#FFFFFF',
    '--surface-overlay': '#FFFFFF',
    '--surface-border': '#D9E2EC',
    '--surface-hover': 'var(--blue-800)', // Darker hover color
    '--text-color': '#102A43', // Slightly brighter text
    '--text-color-secondary': '#334E68', // Brighter secondary text
    '--text-color-sidebar': '#EBF4FF', // Sidebar text color
    '--text-color-sidebar-active': '#FFFFFF', // Sidebar active text color
    '--text-bg-sidebar-active': 'var(--blue-700)', // Sidebar active bg color
    '--primary-color-text': '#102A43',
    '--maskbg': 'rgba(0,0,0,0.2)',
    '--ansi-green': "#008400",
    '--ansi-yellow': "#ecad00",
    '--ansi-blue': "#0000ff",
    '--ansi-magenta': "#ff00ff",
    '--ansi-cyan': "#00ffff",
    '--ansi-white ': "ffffff;",
  };

  _config: AppConfig = {
    ripple: false,
    inputStyle: 'outlined',
    menuMode: 'static',
    colorScheme: 'dark',
    scale: 14,
  };

  config = signal<AppConfig>(this._config);

  state: LayoutState = {
    staticMenuDesktopInactive: false,
    overlayMenuActive: false,
    profileSidebarVisible: false,
    configSidebarVisible: false,
    staticMenuMobileActive: false,
    menuHoverActive: false,
  };

  private overlayOpen = new Subject<any>();
  overlayOpen$ = this.overlayOpen.asObservable();

  constructor(
    private themeService: ThemeService,
    private localStorageService: LocalStorageService
  ) {
    // Load saved theme settings from NVS
    this.themeService.getThemeSettings().subscribe(
      (settings) => {
        if (settings) {
          this._config = {
            ...this._config,
            colorScheme: settings.colorScheme,
          };
          // Apply accent colors if they exist
          if (settings.accentColors) {
            Object.entries(settings.accentColors).forEach(([key, value]) => {
              document.documentElement.style.setProperty(key, value);
            });
          }
        } else {
          // Save default blue light theme if no settings exist
          this.themeService
            .saveThemeSettings({
              colorScheme: 'light',
              accentColors: {
                '--primary-color': '#1e75df',
                '--primary-color-text': '#ffffff',
                '--highlight-bg': '#1e75df',
                '--highlight-text-color': '#ffffff',
                '--focus-ring': '0 0 0 0.2rem #B8D8FF',
                // Slider
                '--slider-bg': '#dee2e6',
                '--slider-range-bg': '#1e75df',
                '--slider-handle-bg': '#1e75df',
                // Progress Bar
                '--progressbar-bg': '#dee2e6',
                '--progressbar-value-bg': '#1e75df',
                // Checkbox
                '--checkbox-border': '#1e75df',
                '--checkbox-bg': '#1e75df',
                '--checkbox-hover-bg': '#3185EC',
                // Button
                '--button-bg': '#1e75df',
                '--button-hover-bg': '#3185EC',
                '--button-focus-shadow': '0 0 0 2px #ffffff, 0 0 0 4px #1e75df',
                // Button Inverted
                '--button-inverted-bg': '#DBEBFF',
                '--button-inverted-hover-bg': '#EBF4FF',
                // Toggle button
                '--togglebutton-bg': '#1e75df',
                '--togglebutton-border': '1px solid #1e75df',
                '--togglebutton-hover-bg': '#3185EC',
                '--togglebutton-hover-border': '1px solid #3185EC',
                '--togglebutton-text-color': '#ffffff',
              },
            })
            .subscribe();
        }
        // Update signal with config
        this.config.set(this._config);
        // Apply initial theme
        this.changeTheme();
      },
      (error) => {
        console.error('Error loading theme settings:', error);
        // Use default theme on error
        this.config.set(this._config);
        this.changeTheme();
      }
    );

    effect(() => {
      const config = this.config();
      this.changeTheme();
      this.changeScale(config.scale);
      this.handleStaticMenuDesktopInactivity();
    });
  }

  onMenuToggle() {
    if (this.isOverlay()) {
      this.state.overlayMenuActive = !this.state.overlayMenuActive;
      if (this.state.overlayMenuActive) {
        this.overlayOpen.next(null);
      }
    }

    if (this.isDesktop()) {
      this.state.staticMenuDesktopInactive =
        !this.state.staticMenuDesktopInactive;

      this.localStorageService.setBool(
        STATIC_MENU_DESKTOP_INACTIVE,
        this.state.staticMenuDesktopInactive
      );
    } else {
      this.state.staticMenuMobileActive = !this.state.staticMenuMobileActive;

      if (this.state.staticMenuMobileActive) {
        this.overlayOpen.next(null);
      }
    }
  }

  showProfileSidebar() {
    this.state.profileSidebarVisible = !this.state.profileSidebarVisible;
    if (this.state.profileSidebarVisible) {
      this.overlayOpen.next(null);
    }
  }

  showConfigSidebar() {
    this.state.configSidebarVisible = true;
  }

  isOverlay() {
    return this.config().menuMode === 'overlay';
  }

  isDesktop() {
    return window.innerWidth > 991;
  }

  isMobile() {
    return !this.isDesktop();
  }

  changeTheme() {
    const config = this.config();

    // Apply light/dark theme variables
    const themeVars =
      config.colorScheme === 'light' ? this.lightTheme : this.darkTheme;
    Object.entries(themeVars).forEach(([key, value]) => {
      document.documentElement.style.setProperty(key, value);
    });

    // Load theme settings from NVS
    this.themeService.getThemeSettings().subscribe(
      (settings) => {
        if (settings && settings.accentColors) {
          Object.entries(settings.accentColors).forEach(([key, value]) => {
            document.documentElement.style.setProperty(key, value);
          });
        }
      },
      (error) => console.error('Error loading accent colors:', error)
    );
  }

  changeScale(value: number) {
    document.documentElement.style.fontSize = `${value}px`;
  }

  handleStaticMenuDesktopInactivity() {
    if (!this.isDesktop()) {
      return;
    }

    this.state.staticMenuDesktopInactive = this.localStorageService.getBool(
      STATIC_MENU_DESKTOP_INACTIVE
    );
  }
}
